<template>
  <ex-dialog
    width="1200px"
    class="ex-diolog"
    :title="title"
    :visible="visible"
    :close-on-click-modal="false"
    @closeDialog="handleClose"
  >
    <div class="main" v-loading="loading">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px" class="demo-ruleForm" :disabled="disabled" >
        <div class="title">活动基本信息</div>
        <el-row>
          <el-col :span="24">
            <el-form-item label="活动名称：" prop="name">
              <el-input
                type="textarea"
                :autosize="{ minRows: 4, maxRows: 8}"
                placeholder="请填写活动名称"
                v-model="ruleForm.name">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动图片:" prop="activityImg"  ref="imgRef">
              <ImageUpload :limit="1" @successImg="successImg" :value="ruleForm.activityImg" @input="handleRemove"></ImageUpload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动时间：" prop="date"> 
              <el-date-picker
                v-model="ruleForm.date"
                @change="getTime"
                type="datetimerange"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                placeholder="选择日期时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动区域：" prop="tradeArea">
              <el-input v-model="ruleForm.tradeArea" placeholder="请填写活动区域" maxlength="50"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" v-if="pathType == 'add'">
            <el-form-item label="活动库存：" prop="stock">
              <el-input placeholder="请输入活动库存" v-model="ruleForm.stock">
                <template slot="append">份</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="pathType == 'edit'">
            <el-form-item label="添加活动库存：" >
              <el-input placeholder="请输入添加活动库存" v-model="ruleForm.stock">
                <template slot="append">份</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4" v-if="pathType == 'edit'">
            <div class="stockNum">剩余库存: {{residueStock}}</div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="限购：" prop="isLimit">
                <el-switch
                  v-model="ruleForm.isLimit"
                  active-value="1"
                  inactive-value="2"
                  active-text="开启"
                  inactive-text="关闭"
                  >
                </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="ruleForm.isLimit == 1">
            <el-form-item label="" label-width="0" prop="limitAmount">
              <el-input placeholder="请输入限购数量" v-model="ruleForm.limitAmount">
                <template slot="append">份</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="title">店铺产品信息</div>
        <el-row v-if="pathType == 'add'">
          <el-col :span="12">
            <el-form-item label="店铺名称：" prop="merchantId">
              <el-select v-model="ruleForm.merchantId" multiple placeholder="请选择店铺" filterable  size="small" @change="changeMerchantId" @remove-tag="removeTag($event)" :disabled="pathType == 'edit'" value-key="shopId">
                <el-option v-for="item in merchantIdList" :key="item.shopId" :label="item.shopName" :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-bottom: 20px">
          <el-col :span="24">
            <el-table :data="ruleForm.shopVOList" border  show-summary>
              <el-table-column label="序号"  type="index" width="50" />
              <el-table-column label="店铺名称" align="center" prop="shopName" :show-overflow-tooltip="true" />
              <el-table-column label="权益图片" align="center" prop="customerPhone" width="240px">
                <template slot-scope="scope">
                  <el-form-item   label="" label-width="0" :prop="'shopVOList.' + scope.$index + '.equityImg'" :rules="rules.equityImg" ref="imgRef">
                    <ImageUpload :isShowTip="false" :limit="1" @successImg="$event => tableSuccessImg($event,scope.$index)" :value="scope.row.equityImg" @input="$event => tableRemove(scope.$index)"></ImageUpload>
                  </el-form-item>
                  <!-- <div class="equityImgBox" v-if="pathType == 'edit'">
                    <img :src="scope.row.equityImg" alt="">
                  </div> -->
                </template>
              </el-table-column>
              <el-table-column label="权益名称" align="center" prop="issuerName">
                <template slot-scope="scope">
                  <el-form-item label="" label-width="0" :prop="'shopVOList.' + scope.$index + '.equityName'" :rules="rules.equityName">
                    <el-input  placeholder="请输入权益名称" v-model="scope.row.equityName" maxlength="50"/>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="价值" align="center" prop="productValue" >
                <template slot-scope="scope">
                  <el-form-item label="" label-width="0" :prop="'shopVOList.' + scope.$index + '.productValue'" :rules="rules.productValue">
                    <el-input  placeholder="请输入价值" v-model="scope.row.productValue" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="售价" align="center" prop="productPrice">
                <template slot-scope="scope">
                  <el-form-item label="" label-width="0" :prop="'shopVOList.' + scope.$index + '.productPrice'" :rules="rules.productPrice">
                    <el-input  placeholder="请输入售价" v-model="scope.row.productPrice" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="成本价" align="center" prop="costPrice">
                <template slot-scope="scope">
                  <el-form-item label="" label-width="0" :prop="'shopVOList.' + scope.$index + '.costPrice'" :rules="rules.costPrice">
                    <el-input  placeholder="请输入成本价" v-model="scope.row.costPrice" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width"  v-if="pathType == 'add'" width="100">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" @click="shopVOListdetele(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <div class="title">激励设置</div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="购买赠送积分：" prop="incentiveVO.integralGive">
                <el-switch
                  v-model="ruleForm.incentiveVO.integralGive"
                  active-value="1"
                  inactive-value="2"
                  active-text="开启"
                  inactive-text="关闭"
                  >
                </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <template v-if="ruleForm.incentiveVO.integralGive == 1">
          <el-row>
            <el-col :span="12">
              <el-form-item label="积分类型：" prop="incentiveVO.integralType">
                <el-select v-model="ruleForm.incentiveVO.integralType" placeholder="请选择积分类型" size="small">
                  <el-option v-for="item in integralTypeList" :key="item.id" :label="item.value" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="激励数额：" prop="incentiveVO.incentiveAmount">
                <el-input placeholder="请输入激励数额" v-model="ruleForm.incentiveVO.incentiveAmount">
                  <template slot="append" v-if="ruleForm.incentiveVO.integralType == 1">CoCo</template>
                  <template slot="append" v-if="ruleForm.incentiveVO.integralType == 2">椰分</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <el-row>
          <el-col :span="12">
            <el-form-item label="打卡奖励：" prop="incentiveVO.punchReward">
                <el-switch
                  v-model="ruleForm.incentiveVO.punchReward"
                  active-value="1"
                  inactive-value="2"
                  active-text="开启"
                  inactive-text="关闭"
                  >
                </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <template v-if="ruleForm.incentiveVO.punchReward == 1">
          <el-row>
            <el-col :span="12">
              <el-form-item label="奖励结束时间：" prop="incentiveVO.rewardEndTime">
                <el-date-picker
                  v-model="ruleForm.incentiveVO.rewardEndTime"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="datetime"
                  placeholder="选择日期时间">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="pathType == 'add'">
            <el-col :span="12">
              <el-form-item label="奖励发放条件：" prop="incentiveVO.conditionId">
                <el-select v-model="ruleForm.incentiveVO.conditionId" multiple placeholder="请选择奖励发放条件" size="small" :disabled="isSel"  @change="changeEquityCardId">
                  <el-option v-for="item in xzAssetList" :key="item.id" :label="item.value" :value="item" value-key="id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="margin-bottom: 20px">
            <el-col :span="24">
              <el-table :data="ruleForm.incentiveVO.incentiveCondVOList"  border>
                <el-table-column label="序号"  type="index" width="50" />
                <el-table-column label="发放条件" align="center" prop="incentiveCond" :show-overflow-tooltip="true" />
                <el-table-column label="选择奖励类型" align="center" prop="customerPhone" :show-overflow-tooltip="true">
                  <template slot-scope="scope">
                    <el-form-item label="" label-width="0" :prop="'incentiveVO.incentiveCondVOList.' + scope.$index + '.incentiveType'" :rules="rules.incentiveType">
                      <el-select :disabled="pathType == 'edit'" v-model="scope.row.incentiveType" placeholder="请选择奖励类型" size="small" @change="changeincentiveType(scope.$index)">
                        <el-option v-for="item in incentiveTypeList" :key="item.id" :label="item.value" :value="item.id">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="奖励名称" align="center" prop="issuerName" :show-overflow-tooltip="true">
                  <template slot-scope="scope" >
                    <el-form-item v-if="scope.row.incentiveType == 1" label="" label-width="0" :prop="'incentiveVO.incentiveCondVOList.' + scope.$index + '.integralType'" :rules="rules.integralType">
                      <el-select :disabled="pathType == 'edit'" v-model="scope.row.integralType" placeholder="请选择积分类型" size="small">
                        <el-option v-for="item in integralTypeList" :key="item.id" :label="item.value" :value="item.id">
                        </el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item v-if="scope.row.incentiveType == 2" label="" label-width="0" :prop="'incentiveVO.incentiveCondVOList.' + scope.$index + '.equityCardId'" :rules="rules.integralType">
                      <el-select :disabled="pathType == 'edit'" v-model="scope.row.equityCardId" placeholder="请选择勋章" size="small">
                        <el-option v-for="item in equityCardList" :key="item.id" :label="item.value" :value="item.id">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </template>
                  
                </el-table-column>
                <el-table-column label="发放数额" align="center" prop="chainTime" :show-overflow-tooltip="true" >
                  <template slot-scope="scope">
                    <el-form-item  v-if="scope.row.incentiveType == 1" label="" label-width="0" :prop="'incentiveVO.incentiveCondVOList.' + scope.$index + '.incentiveAmount'" :rules="rules.incentiveAmount">
                      <el-input :disabled="pathType == 'edit'" placeholder="请输入发放数额" v-model="scope.row.incentiveAmount" />
                    </el-form-item>
                    <el-form-item  v-if="scope.row.incentiveType == 2" label="" label-width="0" :prop="'incentiveVO.incentiveCondVOList.' + scope.$index + '.incentiveAmount'" :rules="rules.incentiveAmount">
                      <el-input :disabled="pathType == 'edit'" placeholder="请输入发放数额" v-model="scope.row.incentiveAmount" />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width"  v-if="pathType == 'add'">
                  <template slot-scope="scope">
                    <el-button size="mini" type="text" @click="incentiveCondVOListdetele(scope.$index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </template>
        <el-row>
          <el-col :span="12">
            <el-form-item label="图文介绍：" prop="introductionStatus">
                <el-switch
                  v-model="ruleForm.introductionStatus"
                  active-value="1"
                  inactive-value="2"
                  active-text="开启"
                  inactive-text="关闭"
                  >
                </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="：" label-width="0" prop="introduction" ref="activityDetailRef"  style="margin-top: 20px" v-if="ruleForm.introductionStatus == 1">
          <WangEditor :value.sync="ruleForm.introduction" @change="useDetailChange($event,1)" style="width:95%;" :lookStatus="disabled"></WangEditor>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动详情：" prop="activityDetailStatus">
                <el-switch
                  v-model="ruleForm.activityDetailStatus"
                  active-value="1"
                  inactive-value="2"
                  active-text="开启"
                  inactive-text="关闭"
                  >
                </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="：" label-width="0" prop="activityDetail" ref="activityDetailRef"  style="margin-top: 20px" v-if="ruleForm.activityDetailStatus == 1">
          <WangEditor :value.sync="ruleForm.activityDetail" @change="useDetailChange($event,2)" style="width:95%;" :lookStatus="disabled"></WangEditor>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动须知：" prop="activityNoticeStatus">
                <el-switch
                  v-model="ruleForm.activityNoticeStatus"
                  active-value="1"
                  inactive-value="2"
                  active-text="开启"
                  inactive-text="关闭"
                  >
                </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="：" label-width="0" prop="activityNotice" ref="activityDetailRef"  style="margin-top: 20px" v-if="ruleForm.activityNoticeStatus == 1">
          <WangEditor :value.sync="ruleForm.activityNotice" @change="useDetailChange($event,3)" style="width:95%;" :lookStatus="disabled"></WangEditor>
        </el-form-item>
      </el-form>
    </div>
    <div class="button_box">
      <el-button
        type="primary"
        :loading="AgreeLoading"
        @click="submitForm('ruleForm',2)"
      >保存提交</el-button>
      <el-button
        type="primary"
        :loading="AgreeLoading"
        @click="submitForm('ruleForm',1)"
        :disabled="pathType == 'edit' && this.ruleForm.status != 1"
      >保存草稿</el-button>
      <el-button @click="handleClose">取消</el-button>
    </div>
  </ex-dialog>
</template>
<script>
import Loading from "@/components/Loading/index";
// api
import {
  addTradePunchActivity,
  editTradePunchActivity,
  activityShopSelect,
  tradePunchDetail,
  activitySelect,
} from "@/api/consumeMiningManagement/checkinActivity";
import '@wangeditor/editor/dist/css/style.css'
import {
  Editor,
  Toolbar
} from "@wangeditor/editor-for-vue";
import WangEditor from '@/components/WangEditor'
export default {
  components: {
    Loading,
    WangEditor,
    Editor,
    Toolbar
  },
  props: {
    visible: Boolean,
    id: String,
    pathType: String,
  },
  data() {
    var checkValidityDay = (rule, value, callback) => {
      let regNumber = /^\+?[1-9]\d*$/; //大于0的正整数
      // console.log(value, this.ruleForm.couponValidityType)
      if (
        !value &&
        this.ruleForm.commodityList[this.arrayIndex].couponValidityType == 2
      ) {
        return callback(new Error("请输入数值"));
      } else if (
        regNumber.test(value) == false &&
        this.ruleForm.commodityList[this.arrayIndex].couponValidityType == 2
      ) {
        return callback(new Error("请输入大于0正整数"));
      } else {
        return callback();
      }
    };
    var checkStock = (rule, value, callback) => {
      //总库存限制数量校验
      let regNumber = /^\+?[1-9]\d*$/; //大于0的正整数
      if (!value) {
        return callback(new Error("请活动库存"));
      } else if (
        regNumber.test(value) == false
      ) {
        return callback(new Error("请输入大于0正整数"));
      } else {
        return callback();
      }
    };
    var checkLimitAmount = (rule, value, callback) => {
      //总库存限制数量校验
      let regNumber = /^\+?[1-9]\d*$/; //大于0的正整数
      if (!value && this.ruleForm.buyType == 2) {
        return callback(new Error("请输入数值"));
      } else if (regNumber.test(value) == false) {
        return callback(new Error("请输入大于0正整数"));
      } else {
        return callback();
      }
    };
    var checkOriginalPrice = (rule, value, callback) => {
      //销售原价校验
      let regNumber = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/; //大于0的数值且最多保留两位小数的数值
      if (regNumber.test(value) == false || value == "0.00" || value == "0.0") {
        return callback(new Error("请填写大于0且最多两位小数的数值"));
      } else {
        return callback();
      }
    };
    var checkIncentiveAmount = (rule, value, callback) => {
      //总库存限制数量校验
      let regNumber = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/; //大于0的数值且最多保留两位小数的数值
      if (!value && this.ruleForm.buyType == 2) {
        return callback(new Error("请输入激励数额"));
      } else if (regNumber.test(value) == false) {
        return callback(new Error("请填写大于0且最多保留两位小数的数值"));
      } else {
        return callback();
      }
    };
    var checkincentiveAmount = (rule, value, callback) => {
      var num = rule.field.substr(32,1)
      console.log('num',num)
      if(this.ruleForm.incentiveVO.incentiveCondVOList[num].incentiveType == 1){
        let regNumber = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/; //大于0的数值且最多保留两位小数的数值
        if (!value && this.ruleForm.buyType == 2) {
          return callback(new Error("请输入激励数额"));
        } else if (regNumber.test(value) == false) {
          return callback(new Error("请填写大于0且最多保留两位小数的数值"));
        } else {
          return callback();
        }
      }else if(this.ruleForm.incentiveVO.incentiveCondVOList[num].incentiveType == 2){
        //总库存限制数量校验
        let regNumber = /^\+?[1-9]\d*$/; //大于0的正整数
        if (!value && this.ruleForm.buyType == 2) {
          return callback(new Error("请输入数值"));
        } else if (regNumber.test(value) == false) {
          return callback(new Error("请输入大于0正整数"));
        } else {
          return callback();
        }
      }
      
    };
    return {
      labelWidth: "150px",
      inputWidth: "420px",
      title: "新增打卡活动",
      loading: false,
      disabled: false,
      AgreeLoading: false,
      ruleForm: {
        status: '',
        name: "", //活动名称
        activityImg: "", //活动图片
        endTime: "", //活动结束时间
        startTime: "", //活动开始时间
        tradeArea: "", //活动区域
        id: "", //打卡活动id编辑必填）
        stock: "", //活动库存
        isLimit: "", //是否限购 1 开启 2 关闭
        limitAmount: "", //限购数量
        merchantId: [],//选择店铺（校验用）
        shopVOList: [//店铺产品列表
          // {
          //   equityImg: '',//权益图片
          //   equityName: '',//权益名称
          //   id: '',//打卡店铺id
          //   productPrice: '',//售价
          //   productValue: '',//价值
          //   shopId: '',//商家店铺id
          //   shopName: '',//店铺名称
          // }
        ],
        incentiveVO: {
          integralGive: '1',//购买赠送积分 1 开启 2 关闭
          integralType: '',//积分类型 1 Coco 2 椰分 shenye_trade_punch_activity_integral_type
          incentiveAmount: '',//激励数额
          punchReward: '1',//打卡奖励 1 开启 2 关闭
          rewardEndTime: '',//奖励结束时间
          conditionId: [],//奖励发放条件（校验用）
          incentiveCondVOList: [
            // {
            //   equityCardId: '',//数字权益卡id
            //   equityCardName: '',//数字权益卡名称
            //   id: '',//激励发放条件id
            //   incentiveAmount: '',//发放数额
            //   incentiveCond: '',//发放条件
            //   incentiveType: '',//奖励类型 1 积分 2 勋章 shenye_trade_punch_activity_incentive_type
            //   integralType: '',//积分类型 1 CoCo 2 椰分 shenye_trade_punch_activity_integral_type
            //   punchShopAmount: '',//打卡门店数
            // },
          ],
        },
        introductionStatus: "1", //图文介绍状态 1 开启 2 关闭
        introduction: "", //图文介绍
        activityDetailStatus: "1", //活动详情状态 1 开始 2 关闭
        activityDetail: "", //活动详情
        activityNoticeStatus: "1", //活动须知状态 1 开始 2 关闭
        activityNotice: "", //活动须知
        date: [], //活动时间（校验用）
      },
      residueStock: 0,
      merchantIdList: [],//店铺下拉列表
      xzAssetList: [],//奖励发放条件列表
      incentiveTypeList: [
        {id: '1',value: '积分'},
        {id: '2',value: '勋章'},
      ],
      integralTypeList: [
        {id: '1',value: 'CoCo'},
        {id: '2',value: '椰分'},
      ],
      equityCardList: [],
      isSel: true,
      rules: {
        name: [
          { required: true,message: "请填写活动名称",trigger: ["change", "bulr"]}
        ],
        activityImg: [
          {required: true, message: "请上传活动图片",trigger: ["change"]}
        ],
        date: [
          {required: true,message: "请选择活动时间",trigger: ["change"]}
        ],
        tradeArea: [
          { required: true,message: "请填写活动区域",trigger: ["change", "bulr"]}
        ],
        stock: [
          { validator: checkStock,required: true,trigger: ["change", "bulr"]}
        ],
        isLimit: [
          { required: true,message: "请选择",trigger: ["change", "bulr"]}
        ],
        limitAmount: [
          { validator: checkLimitAmount, required: true,trigger: ["change", "bulr"]}
        ],
        merchantId: [
          {required: true,message: "请选择店铺",trigger: ["change"]}
        ],

        equityImg: [
          {required: true, message: "请上传权益图片",trigger: ["change"]}
        ],
        equityName: [
          { required: true,message: "请输入权益名称",trigger: ["change", "bulr"]}
        ],
        productValue: [
          { validator: checkOriginalPrice,required: true,trigger: ["change", "bulr"]}
        ],
        productPrice: [
          { validator: checkOriginalPrice,required: true,trigger: ["change", "bulr"]}
        ],
        costPrice: [
          { validator: checkOriginalPrice,required: true,trigger: ["change", "bulr"]}
        ],
        incentiveType: [
          { required: true,message: "请选择奖励类型",trigger: ["change", "bulr"]}
        ],
        integralType: [
          { required: true,message: "请选择奖励名称",trigger: ["change", "bulr"]}
        ],
        equityCardId: [
          { required: true,message: "请选择勋章",trigger: ["change", "bulr"]}
        ],
        incentiveAmount: [
          { validator: checkincentiveAmount,required: true,trigger: ["change", "bulr"]}
          
        ],
        // message: "请输入发放数额",
        
        'incentiveVO.integralGive': [
          { required: true,message: "请选择",trigger: ["change", "bulr"]}
        ],
        'incentiveVO.integralType': [
          { required: true,message: "请选择积分类型",trigger: ["change", "bulr"]}
        ],
        'incentiveVO.incentiveAmount': [
          {  validator: checkIncentiveAmount,required: true,trigger: ["change", "bulr"]}
        ],
        'incentiveVO.punchReward': [
          { required: true,message: "请选择",trigger: ["change", "bulr"]}
        ],
        'incentiveVO.rewardEndTime': [
          { required: true,message: "请选择奖励结束时间",trigger: ["change", "bulr"]}
        ],
        'incentiveVO.conditionId': [
          { required: true,message: "请选择奖励发放条件",trigger: ["change", "bulr"]}
        ],


        introductionStatus: [
          { required: true,message: "请选择",trigger: ["change", "bulr"]}
        ],
        introduction: [
          { required: true,message: "请填写图文介绍",trigger: ["change", "bulr"]}
        ],
        activityDetailStatus: [
          { required: true,message: "请选择",trigger: ["change", "bulr"]}
        ],
        activityDetail: [
          { required: true,message: "请填写活动详情",trigger: ["change", "bulr"]}
        ],
        activityNoticeStatus: [
          { required: true,message: "请选择",trigger: ["change", "bulr"]}
        ],
        activityNotice: [
          { required: true,message: "请填写活动须知",trigger: ["change", "bulr"]}
        ],
       
       
      },
      
    };
  },
  computed: {},
  created() {
    this.getShopSel()
    this.getactivitySelect()
    console.log('this.pathType',this.pathType)
    if(this.pathType == 'edit'){
      this.title = '编辑打卡活动'
      this.ruleForm.id = this.id
      this.getInfo()
    }
   
    // this.getCouponTypeList();
  },
  mounted() {
   
    
  },
  computed: {},
  methods: {
    //获取详情
    getInfo(){
      var id = this.ruleForm.id
      tradePunchDetail(id).then(res => {
        this.ruleForm = {
          ...res.result,
          date: [],
          merchantId: [],
          
        }
        this.ruleForm.incentiveVO.conditionId = []
        this.residueStock = res.result.stock - res.result.soldStock
        this.ruleForm.stock = 0
        
        this.ruleForm.date[0] = res.result.startTime
        this.ruleForm.date[1] = res.result.endTime
        if(this.ruleForm.shopVOList.length > 0){
          this.isSel = false
        }
        this.ruleForm.shopVOList.forEach(item => {
          this.ruleForm.merchantId.push(item.shopId)
        })
        this.ruleForm.incentiveVO.incentiveCondVOList.forEach(item => {
          this.ruleForm.incentiveVO.conditionId.push(item.id)
          var data = {
            id: item.id,
            value: item.incentiveCond,
            num: item.punchShopAmount,
          }
          this.xzAssetList.push(data)
        })
        console.log('this.ruleForm',this.ruleForm)
      })
    },
   
    //获取店铺下拉
    getShopSel(){
      activityShopSelect().then(res => {
        this.merchantIdList = res.result
      })
    },
    //获取勋章  
    getactivitySelect(){
      activitySelect().then(res => {
        this.equityCardList = res.result
      })
    },
    //选择店铺
    changeMerchantId(e){
      var list = e
      if(list.length > 0){
        this.isSel = false
      }else{
        this.isSel = true
      }
      this.ruleForm.shopVOList = e
      // var obj = {
      //     equityImg: '',//权益图片
      //     equityName: '',//权益名称
      //     id: '',//打卡店铺id
      //     productPrice: '',//售价
      //     productValue: '',//价值
      //     shopId: '',//商家店铺id
      //     shopName: '',//店铺名称
      //   }
      // list.forEach((item,index) => {
      //   obj.shopId = item
      //   this.merchantIdList.forEach(aitem => {
      //     if(item == aitem.id){
      //       obj.shopName = aitem.value
      //     }
      //   })
      // });
      // this.ruleForm.shopVOList.push(obj)
      // this.ruleForm.shopVOList = []
      // list.forEach(item => {
      //     this.merchantIdList.forEach(aitem => {
      //         if (item == aitem.id) {
      //           var obj = {
      //               equityImg: '',//权益图片
      //               equityName: '',//权益名称
      //               id: '',//打卡店铺id
      //               productPrice: '',//售价
      //               productValue: '',//价值
      //               shopId: '',//商家店铺id
      //               shopName: '',//店铺名称
      //             }
      //             obj.shopId = item
      //             obj.shopName = aitem.value
      //             this.ruleForm.shopVOList.push(obj)
      //         }
      //     })
      // })
      this.generateList()
    },
    //生成奖励发放条件
    generateList(){
      // this.ruleForm.incentiveVO.conditionId = []
      this.xzAssetList = []
      this.ruleForm.shopVOList.forEach((item,index) => {
        var data = {
          id: 0,
          value: 1,
          num: 1,
          equityCardId: '',//数字权益卡id
          equityCardName: '',//数字权益卡名称
          id: '',//激励发放条件id
          incentiveAmount: '',//发放数额
          incentiveCond: '',//发放条件
          incentiveType: '',//奖励类型 1 积分 2 勋章 shenye_trade_punch_activity_incentive_type
          integralType: '',//积分类型 1 CoCo 2 椰分 shenye_trade_punch_activity_integral_type
          punchShopAmount: '',//打卡门店数
        }
        data.id = data.id + index
        data.value = `打卡${data.value + index}家门店` 
        data.num = data.num + index

        data.incentiveCond = data.value
        data.punchShopAmount =  data.num
        console.log('this.xzAssetList',data)
        this.xzAssetList.push(data)
      })
    },
    //奖励发放条件
    changeEquityCardId(e){
      console.log('e',e)
      this.ruleForm.incentiveVO.incentiveCondVOList = e
      console.log('this.ruleForm.incentiveVO.incentiveCondVOList',this.ruleForm.incentiveVO.incentiveCondVOList)
      // var obj = {
      //   equityCardId: '',//数字权益卡id
      //   equityCardName: '',//数字权益卡名称
      //   id: '',//激励发放条件id
      //   incentiveAmount: '',//发放数额
      //   incentiveCond: '',//发放条件
      //   incentiveType: '',//奖励类型 1 积分 2 勋章 shenye_trade_punch_activity_incentive_type
      //   integralType: '',//积分类型 1 CoCo 2 椰分 shenye_trade_punch_activity_integral_type
      //   punchShopAmount: '',//打卡门店数
      // }
      // list.forEach((item,index) => {
      //   this.xzAssetList.forEach(aitem => {
      //     if(item == aitem.id){
      //       obj.incentiveCond = aitem.value
      //       obj.punchShopAmount = aitem.num
      //      }
      //   })
      // })
      // this.ruleForm.incentiveVO.incentiveCondVOList.push(obj)
      console.log('发放条件',this.ruleForm.incentiveVO.incentiveCondVOList)
    },
    changeincentiveType(index){
      console.log('index',index)
      this.ruleForm.incentiveVO.incentiveCondVOList[index].incentiveAmount = ''
    },
    //删除奖励发放条件
    incentiveCondVOListdetele(e){
      this.ruleForm.incentiveVO.incentiveCondVOList.splice(e,1)
    },
    //取消
    handleClose(formName) {
      this.$emit("update:visible", false);
    },
  
    // 删除卡名称列表
    handleDel(index,row){
      this.$confirm('是否删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log(index)
          this.ruleForm.blockNameList.splice(index,1)
        }).catch(() => {});
    },
    successImg(e) {
      this.ruleForm.activityImg = e
      this.$refs['imgRef'].clearValidate();
    },
    // 删除图片
    handleRemove(){
      this.ruleForm.activityImg = ''
    },
    //table上传图片
    tableSuccessImg(e,ind){
      this.ruleForm.shopVOList[ind].equityImg = e
    },
    tableRemove(ind){
      this.ruleForm.shopVOList[ind].equityImg = ''
    },
    //删除店铺产品信息
    shopVOListdetele(e){
      console.log('this.ruleForm.merchantId',this.ruleForm.merchantId)
      this.ruleForm.shopVOList.splice(e,1)
      // this.ruleForm.merchantId.splice(e,1)
      this.generateList()
      var index = this.ruleForm.incentiveVO.conditionId.length - 1
      // this.ruleForm.incentiveVO.conditionId = []
      // this.ruleForm.incentiveVO.incentiveCondVOList = []
      this.ruleForm.incentiveVO.conditionId.splice(index,1)
      this.ruleForm.incentiveVO.incentiveCondVOList.splice(index,1)

    },
    removeTag(e,index){
      this.generateList()
      var index = this.ruleForm.incentiveVO.conditionId.length - 1
      this.ruleForm.incentiveVO.conditionId.splice(index,1)
      this.ruleForm.incentiveVO.incentiveCondVOList.splice(index,1)
    },
    getTime(e){
      console.log("e",e)
      this.ruleForm.startTime =  e[0] 
      this.ruleForm.endTime = e[1]
      console.log("e",this.ruleForm.startTime)
      console.log("e",this.ruleForm.endTime)
    },
    
    submitForm(formName, status) {
      this.ruleForm.saveStatus = status
      console.log(this.ruleForm);
      //创建确定
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.AgreeLoading = true
          
          var data = {
            ...this.ruleForm
          }
          // data.merchantId = data.merchantId.map(vo=>{
          //   return vo.shopId
          // })
          if(this.pathType == 'add'){
            addTradePunchActivity(data).then(res => {
              setTimeout(() => {
                this.handleClose()
                this.$message.success('创建成功')
                this.$emit('success')
                this.AgreeLoading = false
              }, 1000);
            }).finally(()=>{
              this.AgreeLoading = false
            })
          }else if(this.pathType == 'edit'){
            editTradePunchActivity(data).then(res => {
              setTimeout(() => {
                this.handleClose()
                this.$message.success('修改成功')
                this.$emit('success')
                this.AgreeLoading = false
              }, 1000);
            }).finally(()=>{
              this.AgreeLoading = false
            })
          }
          
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    editForm(formName, status) {
      //编辑确定
      console.log(this.ruleForm);
      this.$refs[formName].validate(valid => {
        if (valid) {
          
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    
    // 富文本框设置
    useDetailChange(e,index){
      if(e != ''){
        // this.$refs.ruleForm.clearValidate(['commodityList.'+index+'.useDetail']);
      }
      // console.log(e,index)
      // console.log(this.ruleForm.)
    }
  }
};
</script>
<style lang="scss" scoped>
.ex-diolog {
  ::v-deep .ex--dialog--footer {
    border: none !important;
    padding: 0 !important;
  }

  ::v-deep .ex--dialog--main {
    padding: 10px 20px !important;
  }
}
.el-select{
  width: 100%;
}
.main {
  padding: 20px 20px;
}
.title{
  font-size: 18px;
  font-weight: bold;
  color: #1890ff;
  padding: 10px 0;
  border-bottom: 4px solid #1890ff;
  margin-bottom: 20px;
}
.richText {
  border: 1px solid #ccc;
  line-height: normal;
}
.stockNum{
  display: flex;
  justify-content: center;
  padding-top: 10px;
}
.button_box{
  display: flex;
  justify-content: center;
}
.equityImgBox{
  width: 100%;
  display: flex;
  justify-content: center;
}
.equityImgBox img{
  width: 120px;
  height: 120px;
}
.el-form-item{
  margin-bottom: 32px;
}
</style>
